package com.gcb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.gcb.common.enums.AuthStatusEnum;
import com.gcb.common.exception.ServiceException;
import com.gcb.domain.dto.company.CompanyWaterAuthDTO;
import com.gcb.domain.entity.Company;
import com.gcb.domain.dto.company.CompanyAuthDTO;
import com.gcb.domain.vo.company.CompanyAuthVO;
import com.gcb.service.ICompanyAuthService;
import com.gcb.service.ICompanyService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 企业认证信息Service业务层处理
 *
 * @author tdl
 * @since 2024-04-07
 */
@Service
public class CompanyAuthServiceImpl implements ICompanyAuthService {

    @Resource
    private ICompanyService companyService;

    @Override
    public CompanyAuthVO getAuth(Long companyId) {
        Company company = companyService.selectCompanyById(companyId);
        if (Objects.isNull(company)) {
            throw new ServiceException("企业不存在");
        }

        CompanyAuthVO vo = new CompanyAuthVO();
        BeanUtils.copyProperties(company, vo);
        return vo;
    }

    @Override
    public Boolean saveAuth(CompanyAuthDTO dto, Long currentId) {
        Company company = companyService.selectCompanyById(dto.getId());
        Validator.validateNotNull(company, "企业不存在");

        BeanUtil.copyProperties(dto, company);
        Date authTime = company.getAuthTime();
        if (Validator.isNull(authTime)) {
            company.setAuthTime(new Date());
        }
        company.setAuthUpdateTime(new Date());
        company.setAuthStatus(AuthStatusEnum.VERIFIED.getCode());
        company.setUpdateBy(Long.valueOf(String.valueOf(currentId)));
        company.setUpdateTime(new Date());
        return companyService.saveOrUpdate(company);
    }

    @Override
    public Boolean saveWaterAuth(CompanyWaterAuthDTO dto, Long currentId) {
        Company company = companyService.selectCompanyById(dto.getId());
        if (Objects.isNull(company)) {
            throw new ServiceException("企业不存在");
        }

        BeanUtils.copyProperties(dto, company);
        Integer status = company.getStatus();
        Date waterAuthTime = company.getWaterAuthTime();
        company.setWaterStatus(AuthStatusEnum.VERIFIED.getCode());
        if (Validator.isNull(waterAuthTime)) {
            company.setWaterAuthTime(new Date());
        }
        company.setWaterAuthUpdateTime(new Date());
        company.setUpdateBy(Long.valueOf(String.valueOf(currentId)));
        company.setUpdateTime(new Date());
        return companyService.saveOrUpdate(company);
    }
}
